package handler

import (
	"encoding/json"
	"strconv"
	"time"
	"wei-bo-sys/cache"
	"wei-bo-sys/models"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	var wei []models.WeiBo
	models.DB.Debug().Find(&wei)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": wei,
	})
	return
}
func List2(c *gin.Context) {
	name := c.PostForm("name")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var wei []models.WeiBo
	redis_key := "list_" + name
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Where("name=?", name).Debug().Find(&wei)
		jsonData, _ := json.Marshal(&wei)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &wei)
	}
	var total int64
	models.DB.Model(&wei).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  wei,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var wei models.WeiBo
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Debug().Find(&wei)
		jsonData, _ := json.Marshal(&wei)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &wei)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": wei,
	})
	return
}
func CommentList(c *gin.Context) {
	wid := c.PostForm("wid")
	var comment []models.Comment
	redis_key := "comment_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("wid=?", wid).Order("id desc").Debug().Find(&comment)
		jsonData, _ := json.Marshal(&comment)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comment)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": comment,
	})
	return
}
